<template>
  <el-card class="app-container">
    <div v-if="!detailShow">
      <div class="itemTitle">风险检查表管理</div>
      <div class="search">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
          <el-col :span="5">
            <el-form-item label="检查表名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入检查表名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="检查类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择检查类型" clearable>
                <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div class="content">
        <div class="ct-btns">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['risk:check:add']">新增</el-button>
        </div>
        <div class="ct-table">
          <elTables :table-data="tableData" :columns="tableColumns" :totalLength="total" :currentPage="queryParams.pageNum"
            :handle-current-change="handleCurrentChange" isPagin :curHeight="tableHeight" />
        </div>
      </div>
    </div>
    <!-- 添加或修改风险检查对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body @close="cancel" class="dialog-form">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-col :span="12">
          <el-form-item label="检查表名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入检查表名称" :readonly="!isEdit" :disabled="!isEdit" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="检查类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择检查类型" :readonly="!isEdit" :disabled="!isEdit">
              <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <AddItems v-if="detailShow" :info="form" @closeAddItems="handleCloseAddItems"/>
  </el-card>
</template>

<script>
const defaultQueryParams = {
  pageNum: 1,
  pageSize: 10,
};
import { getToken } from "@/utils/auth";
import { pageCheck,getCheck, delCheck, addCheck, updateCheck, exportCheck,getBatchCheckItem } from "@/api/risk/check";
import AddItems from './addItem.vue'
export default {
  name: "Check",
  components:{ AddItems },
  data() {
    return {
      tableHeight: 0,
      isEdit: false,
      dialogFormVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API + "/risk/check/importData",
      },
      tableData: [],
      // 检查类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        ...defaultQueryParams,
        name: null,
        type: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "检查表名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "检查类型不能为空", trigger: "change" }
        ],
      },
      tableColumns: [
        { key: "name", title: "检查表名称" },
        { key: "type", title: "检查类型", render:(h,params) => {
          return h('div',{},this.typeOptions.find(_ => _.dictValue == params.row.type)?.dictLabel)
        }},
        {
          title: "操作",
          align: "center",
          fixed: 'right',
          width: 260,
          render: (h, params) => {
            return h("div", [
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:check:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleAddItems(params.row)
                    },
                  },
                },
                "添加检查项"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:check:info"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 2)
                    },
                  },
                },
                "查看"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:check:edit"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleUpdate(params.row, 1);
                    },
                  },
                },
                "编辑"
              ),
              h(
                "el-button",
                {
                  props: {
                    type: "text",
                    size: "small",
                  },
                  directives: [
                    {
                      name: "hasPermi",
                      value: ["risk:check:remove"],
                    },
                  ],
                  on: {
                    click: () => {
                      this.handleDelete(params.row)
                    },
                  },
                },
                "删除"
              ),
            ]);
          },
        },
      ],
      detailShow:false,
    };
  },
  created() {
    this.getPage();
    this.getDicts("check_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.getTableHeight();
    })
  },
  methods: {
    handleAddItems(row){
      console.log('row',row)
      this.detailShow=true;
      const id = row.id || this.ids
      getCheck(id).then(response => {
        this.form = response.data;
      });
    },
    handleCloseAddItems(){
      this.detailShow=false;
    },
    handleAddByDialog() {
      this.dialogFormVisible = true;
    },
    getTableHeight() {
      let height = document.getElementsByClassName('ct-table')[0].clientHeight;
      this.tableHeight = height - 40;
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getPage();
    },
    /** 查询风险检查列表 */
    getPage() {
      this.loading = true;
      pageCheck(this.queryParams).then(response => {
        this.tableData = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 检查类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        type: null,
        factoryId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        createDept: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isEdit = true;
      this.title = "新增风险检查";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      if (type == 1) {
        this.isEdit = true;
        this.title = "编辑风险检查";
      } else {
        this.isEdit = false;
        this.title = "查看风险检查";
      }
      this.reset();
      const id = row.id || this.ids
      getCheck(id).then(response => {
        this.form = response.data;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCheck(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getPage();
            });
          } else {
            addCheck(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getPage();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        let data
        if (Array.isArray(ids)) {
          data = ids
        } else {
          data = [ids]
        }
        return delCheck(data);
      }).then(() => {
        this.getPage();
        this.msgSuccess("删除成功");
      })
    },
  }
};
</script>
<style lang="scss" scoped></style>